# -*- coding: utf-8 -*-
# @Author : Joey Zhang
# @Time : 2023/2/15 14:39

import random
import tkinter as tk
from tkinter import messagebox, ttk
import openai

apikey = ''


def chat(question):
    try:
        openai.api_key = str(key.get())
        # openai.api_key = OPENAI_API_KEY
        environment_name = "text-davinci-003"
        env = openai.Completion(engine=environment_name)

        response = env.create(
            engine="text-davinci-003",
            prompt=question,
            max_tokens=500,
            temperature=3,
            timeout=1
        )
        answer = "ChatGPT:" + response.choices[0].text
        # answer = "ChatGPT: just for test" + question + str(key.get())
    except Exception as e:
        print(f" openai invoke error: {e}")
        return "ERROR: can't connect OpenAI"
    return answer


# translate
def translate(event):
    prompt = "translate " + "\'" + origin_text.get() + "\'" + " to " + cbox.get()
    answer = chat(prompt)
    translate_text.insert(tk.END, answer + "\n")


# Grammar correction
def Grammaly(event):
    prompt = "Correct this to standard English:\n\n" + entry_gram.get()
    answer = chat(prompt)
    translate_text.insert(tk.END, answer + "\n")


def generate_image(event):
    des = entry_dali.get()
    try:
        # openai.api_key = str(key.get())
        openai.api_key = apikey
        response = openai.Image.create(
            prompt=des,
            n=1,
            size="1024x1024"
        )
        image_url = response['data'][0]['url']
        suffix = str(random.randint(1, 1000))
        from urllib.request import urlretrieve
        urlretrieve(image_url, 'generate' + suffix + '.png')
    except Exception as e:
        print(f" openai dali invoke error: {e}")


def ask(event):
    question = e1.get()
    answer = chat(question)
    question = "Me:" + question

    e2.insert(tk.END, question + "\n")
    e2.insert(tk.END, answer + "\n")


def active(event):
    tk.messagebox.askyesno(title='activa', message='APIKEY has been activated.')


# def active_user():
#     global apikey
#     param = {
#         "username": user_entry.get(),
#         "pwd": pass_entry.get()
#     }
#     url = 'http://127.0.0.1:5006/login'
#     response = requests.post(url=url, data=param, timeout=20)
#     api_key = response.json()['APIKEY']
#     if api_key != "ERROR":
#         api_key = b64decode(api_key)
#         en_key = b64decode(response.json()['en_key'])
#         apikey = My_AES_CBC(en_key, iv='1234567890123456'.encode('utf-8')).decrypt(api_key)
#
#         messagebox.showinfo(title='active key', message='user ok')
#     else:
#
#         messagebox.showinfo(title='active key', message='user expire')


win = tk.Tk()
win.title("Chat Robot")
# win.iconbitmap('C:/Users/Administrator/Desktop/C语言中文网logo.ico')
win.geometry('1000x800+100+100')
win.resizable(0, 0)
# 将俩个标签分别布置在第一行、第二行
tk.Label(win, text="Chat：").grid(row=0)
# tk.Label(win, text="Chat History：").grid(row=1)
label_dali = tk.Label(win, text="Image Generate：")
label_dali.grid(row=3)

# 创建输入框控件
e1 = tk.Entry(win, width=120)
e2 = tk.Text(win, width=120, height=30)
e1.grid(row=0, column=1, padx=10, pady=5)
e2.grid(row=1, column=1, padx=10, pady=5)
e1.bind('<Return>', ask)

# dali image generate
entry_dali = tk.Entry(win, width=120)
entry_dali.grid(row=3, column=1, padx=10, pady=5)
entry_dali.insert(0, "input the words describe the picture you want to generate")
entry_dali.bind('<Return>', generate_image)

# translate
tk.Label(win, text="Translate：").grid(row=4)
origin_text = tk.Entry(win, width=120)
origin_text.grid(row=4, column=1, padx=10, pady=5)
# tk.Label(win, text="To：").grid(row=5)
cbox = ttk.Combobox(win)
cbox.grid(row=5, column=1, sticky='w', padx=10, pady=5)
cbox['value'] = ('English', 'Chinese', 'Japanese', 'Korea')
cbox.current(1)
cbox.bind('<<ComboboxSelected>>', translate)
translate_text = tk.Text(win, width=120, height=5)
translate_text.grid(row=6, column=1)

# Grammar correction
label_gram = tk.Label(win, text="Grammar correction：")
label_gram.grid(row=7)
entry_gram = tk.Entry(win, width=120)
entry_gram.grid(row=7, column=1, padx=10, pady=5)
entry_gram.insert(0, "input the text you want to correct grammar")
entry_gram.bind('<Return>', Grammaly)
correct_text = tk.Text(win, width=120, height=5)
correct_text.grid(row=8, column=1)

# activa the key
tk.Label(win, text="API Key：").grid(row=16)
key = tk.StringVar()
e3 = tk.Entry(win, width=120)
e3["textvariable"] = key
e3.grid(row=16, column=1, padx=10, pady=5)
e3.bind('<Return>', active)

# tk.Label(win, text="user：").grid(row=16)
# tk.Label(win, text="password：").grid(row=17)
# user_entry = tk.Entry(win, width=60)
# user_entry.grid(row=16, column=1, padx=10, pady=5, sticky='w')
# pass_entry = tk.Entry(win, show='*', width=60)
# pass_entry.grid(row=17, column=1, padx=10, pady=5, sticky='w')
# tk.Button(win, text="check", width=10, command=active_user).grid(row=18, column=1, sticky="w", padx=10, pady=5)

tk.Label(win, text="Copyright by Joey@2023").grid(row=18, column=1, sticky="se", padx=10, pady=5)

win.mainloop()
